package com.example.qihuibao.widget.view

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.bean.*
import com.example.qihuibao.dao.MyDatabase
import com.example.qihuibao.enum.FlowType
import com.example.qihuibao.enum.OrderMode
import com.example.qihuibao.enum.Status
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.EnumUtils
import com.example.qihuibao.utils.extension.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.intellij.lang.annotations.Flow

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :
 */
class CanteenInfoLayout(ctx:Context) : FrameLayout(ctx) {
    private lateinit var activity: MainActivity
    private lateinit var root: View
    private var modify = false
    private var empTypes : List<EmpType>? = null
    private val cantList = mutableListOf<Cant>()
    private lateinit var rv_canteen: CommonRecyclerView

    private var selectStat: Status? = null
    private var selectFlowType: FlowType? = null
    private var selectOrderMode: OrderMode? = null
    private var rspQueryCanteenInfoBean: RspQueryCanteenInfoBean? = null

    init {
        if (ctx is MainActivity) {
            activity = ctx
        }
        root = LayoutInflater.from(ctx).inflate(R.layout.layout_canteen, this, true)
        root.setOnClickListener {  }//禁止点击事件穿透
        initView()
    }

    private fun initView() {
        root.findViewById<TextView>(R.id.tv_title).text = "餐厅信息"
        root.findViewById<View>(R.id.iv_back).setOnClickListener { (parent as ViewGroup).removeView(this) }
        root.findViewById<View>(R.id.tv_update).setOnClickListener { update() }
//        root.findViewById<View>(R.id.tv_add).setOnClickListener { add() }
//        root.findViewById<View>(R.id.tv_delete).setOnClickListener { delete() }
        queryEnterpriseInfo()
    }

    private fun queryEnterpriseInfo() {
        activity?.getMainViewModel().queryEnterpriseInfo().observe(activity) {
            if (it.RetCode == "0") {
                if (!it.CantList.isNullOrEmpty()) {
                    empTypes = it.EmpTypeList
                    cantList.clear()
                    cantList.addAll(it.CantList)
                    //
                    rv_canteen = root.findViewById<CommonRecyclerView>(R.id.rv_canteen)
                    rv_canteen.init(
                        R.layout.item_text,
                        LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                        cantList,
                        { parent, pos ->
                            if (cantList.isNotEmpty()) {
                                (parent as TextView).text = "餐厅ID：${cantList[pos].CantID}\n" +
                                        "餐厅名称：${cantList[pos].CantName}\n" +
                                        "状态：${if (cantList[pos].Status == "0") "正常" else "冻结"}"
                            }
                        },
                        {pos ->
                            showDetail(cantList[pos])
                        }
                    )
                }
            }else {
                activity?.toast("查询失败")
            }
        }
    }

    private fun showDetail(cant:Cant) {
        val req = ReqQueryCanteenInfoBean("${cant.CantID}")
        activity.getMainViewModel().queryCanteenInfo(req).observe(activity) {
            if (it.RetCode == "0") {
                rspQueryCanteenInfoBean = it
                root.findViewById<EdittextWithText>(R.id.et_CantID).setContent("${it.CantID}")
                root.findViewById<EdittextWithText>(R.id.et_CantName).setContent("${it.CantName}")
                val stats = EnumUtils.getStatus(it.Status?:"0")
                selectStat = stats[0]
                val spStatus = root.findViewById<Spinner>(R.id.sp_Status)
                spStatus?.adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, stats)
                spStatus?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectStat = stats[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                root.findViewById<CheckBox>(R.id.cb_ServiceType1).isChecked = EnumUtils.getEnable("${it.ServiceType}", 1)
                root.findViewById<CheckBox>(R.id.cb_ServiceType2).isChecked = EnumUtils.getEnable("${it.ServiceType}", 2)
                root.findViewById<CheckBox>(R.id.cb_ServiceType3).isChecked = EnumUtils.getEnable("${it.ServiceType}", 3)
                root.findViewById<CheckBox>(R.id.cb_ServiceType4).isChecked = EnumUtils.getEnable("${it.ServiceType}", 4)
                root.findViewById<CheckBox>(R.id.cb_ServiceType6).isChecked = EnumUtils.getEnable("${it.ServiceType}", 6)
                root.findViewById<CheckBox>(R.id.cb_ServiceType7).isChecked = EnumUtils.getEnable("${it.ServiceType}", 7)
                root.findViewById<CheckBox>(R.id.cb_UseMode1).isChecked = EnumUtils.getEnable("${it.UseMode}", 1)
                root.findViewById<CheckBox>(R.id.cb_UseMode2).isChecked = EnumUtils.getEnable("${it.UseMode}", 2)
                root.findViewById<CheckBox>(R.id.cb_UseMode3).isChecked = EnumUtils.getEnable("${it.UseMode}", 3)
                val flowTypes = EnumUtils.getFlowType(it.FlowType?:"0")
                selectFlowType = flowTypes[0]
                val spFlowType = root.findViewById<Spinner>(R.id.sp_FlowType)
                spFlowType?.adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, flowTypes)
                spFlowType?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectFlowType = flowTypes[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                root.findViewById<CheckBox>(R.id.cb_QryBalanceFlag).isChecked = it.QryBalanceFlag == "1"
                root.findViewById<CheckBox>(R.id.cb_QryConsumeFlag).isChecked = it.QryConsumeFlag == "1"
                root.findViewById<CheckBox>(R.id.cb_SecondAccFlag).isChecked = it.SecondAccFlag == "1"
                root.findViewById<CheckBox>(R.id.cb_OpenChannel1).isChecked = EnumUtils.getEnable("${it.OpenChannel}", 1)
                root.findViewById<CheckBox>(R.id.cb_OpenChannel2).isChecked = EnumUtils.getEnable("${it.OpenChannel}", 2)
                root.findViewById<CheckBox>(R.id.cb_OpenChannel5).isChecked = EnumUtils.getEnable("${it.OpenChannel}", 5)
                val orderModes = EnumUtils.getOrderMode(it.OrderMode?:"0")
                selectOrderMode = orderModes[0]
                val spOrderMode = root.findViewById<Spinner>(R.id.sp_OrderMode)
                spOrderMode?.adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, orderModes)
                spOrderMode?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectOrderMode = orderModes[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                root.findViewById<CommonRecyclerView>(R.id.rv_EmpTypeList).init(
                    R.layout.item_checkbox,
                    LinearLayoutManager(context, RecyclerView.HORIZONTAL, false),
                    empTypes,
                    { parent, pos ->
                        val checkBox:CheckBox = (parent as CheckBox)
                        checkBox.text = "${empTypes!![pos].EmpTypeName}"
                        checkBox.setTextColor(Color.BLACK)
                        checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
                            empTypes!![pos].select = isChecked
                        }
                        checkBox.isChecked = false
                        if (!rspQueryCanteenInfoBean?.EmpTypeList.isNullOrEmpty()) {
                            for (item in rspQueryCanteenInfoBean!!.EmpTypeList!!) {
                                if (empTypes!![pos].EmpTypeID == item .EmpTypeID) {
                                    checkBox.isChecked = true
                                    break
                                }
                            }
                        }
                    }
                )
                root.findViewById<CommonRecyclerView>(R.id.rv_DiscountList).init(
                    R.layout.item_text,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    it.DiscountList,
                    { parent, pos ->
                        (parent as TextView).text = "优惠ID：${it.DiscountList!![pos].DiscountID}\n" +
                                "优惠名称：${it.DiscountList!![pos].DiscountName}"
                    }
                )
            }else {
                activity?.toast("查询失败")
            }
        }
    }

    private fun update() {
        val list = mutableListOf<EmpType>()
        if (!empTypes.isNullOrEmpty()) {
            for (item in empTypes!!) {
                if (item.select) {
                    list.add(item)
                }
            }
        }
        val req = ReqUpdateCanteenInfoBean(
            CantID = "${rspQueryCanteenInfoBean?.CantID}",
            Status = "${selectStat?.value}",
            UseMode = "${if (root.findViewById<CheckBox>(R.id.cb_UseMode1).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_UseMode2).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_UseMode3).isChecked) "1" else "0"}",
            FlowType = "${selectFlowType?.value}",
            SecondAccFlag = "${if (root.findViewById<CheckBox>(R.id.cb_SecondAccFlag).isChecked) "1" else "0"}",
            EmpTypeList = list
        )
        activity.getMainViewModel().updateCanteenInfo(req).observe(activity) {
            activity.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
            if (it.RetCode == "0") {
                queryEnterpriseInfo()
            }
        }
    }
}